﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;

/// <summary>
///ExportFile 的摘要说明
/// </summary>
public class ExportFile
{  
    /// <summary>
    /// 将DataSet导出成CSV格式
    /// </summary>
    /// <param name="ds">DataSet</param>
    /// <returns>CSV字符串数据</returns>
    private  string ExportCSV(DataTable tb)//DataSet ds
    {
       System.Text.StringBuilder data = new System.Text.StringBuilder();

        //写出列名
        foreach (DataColumn column in tb.Columns)
        {
            if (IsExport(column))
                data.Append(column.ExtendedProperties["FieldCHS"].ToString() + ",");   //column.ColumnName + ",";
        }
        data.Append("\n");

        //写出数据
        foreach (DataRow row in tb.Rows)
        {
            foreach (DataColumn column in tb.Columns)
            {
                //判断列是否导出 
                if (IsExport(column))
                    //data.Append(row[column].ToString().Replace(",", "，") + ",");
                data.Append(row[column].ToString().Replace(",", "，").Replace("\n", " ") + ",");
            }
            data.Append("\n");
        }
        return data.ToString();
    }

    /// <summary>
    /// 标记DataColumn为接受导出的
    /// </summary>
    /// <param name="column">DataColumn</param>
    private  void SetExport(DataColumn column, string headertext)
    {
        if (column != null)
        {
            //将列推到集合的最后，以便输出的时候按顺序输出
            column.SetOrdinal(column.Table.Columns.Count - 1);

            if (column.ExtendedProperties["IsExport"] == null)
                column.ExtendedProperties.Add("IsExport", "true");
            else
                column.ExtendedProperties["IsExport"] = "true";
            //保存列的中文名
            if (column.ExtendedProperties["FieldCHS"] == null)
                column.ExtendedProperties.Add("FieldCHS", headertext);
            else
                column.ExtendedProperties["FieldCHS"] = headertext;
        }
    }

    /// <summary>
    /// 标记DataTable中的一些列为接受导出的
    /// </summary>
    /// <param name="tb">DataTable</param>
    /// <param name="columns">列</param>
    //private static void SetExport(DataTable tb, params string[] columns)
    //{
    //    foreach (string column in columns)
    //    {
    //        SetExport(tb.Columns[column]);
    //    }
    //}

    /// <summary>
    /// 标记DataTable中的一些列为接受导出的
    /// </summary>
    /// <param name="tb">DataTable</param>
    /// <param name="columns">DataGrid的列</param>
    private  void SetExport(DataTable tb, DataControlFieldCollection columns)//DataGridColumnCollection
    {
        foreach (DataControlField column in columns)//DataGridColumn
        {
            if (column.GetType().Name.ToLower() == "boundfield")
            {
                SetExport(tb.Columns[(column as BoundField).DataField], (column as BoundField).HeaderText);//column.HeaderText
            }
        }
    }

    /// <summary>
    /// 判断DataColumn是否为接受导出的
    /// </summary>
    /// <param name="column">DataColumn</param>
    /// <returns>bool型的结果</returns>
    private  bool IsExport(DataColumn column)
    {
        if (column.ExtendedProperties["IsExport"] != null && column.ExtendedProperties["IsExport"].ToString().Trim().ToLower() == "true")
            return true;
        else
            return false;
    }


    public void ExportData(DataTable dt, GridView gvwinfo,System.Web.UI.Page Page)
    {
       

        SetExport(dt, gvwinfo.Columns);

        string data = ExportCSV(dt); // Export.ExportCSV(ds);

        Page.Response.Clear();
        Page.Response.Buffer = true;
        Page.Response.Charset = "GB2312";
        string temp = string.Format("attachment;filename={0}", "ExportData.csv");
        Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Page.Response.ClearHeaders();
        Page.Response.AppendHeader("Content-disposition", temp);
        Page.Response.Write(data);
        Page.Response.End();
    }
 

   
    public static ExportFile Instance
    {
        get { return new ExportFile(); }
    }
}
